package com.bank.backend.interceptor;

import com.bank.backend.annotation.AuthCheck;
import com.bank.backend.enums.ErrorCode;
import com.bank.backend.enums.UserRoleEnum;
import com.bank.backend.exception.BusinessException;
import com.bank.backend.utils.UserHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 权限校验 AOP
 */
@Aspect
@Component
@Slf4j
public class AuthInterceptor {

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        // 从UserHolder获取当前用户信息
        Integer userId = UserHolder.getUserId();
        Boolean isAdmin = UserHolder.getIsAdmin();

        if (userId == null || isAdmin == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        UserRoleEnum mustRoleEnum = UserRoleEnum.getByValue(mustRole);
        // 根据用户的isAdmin字段判断角色
        UserRoleEnum userRoleEnum = UserRoleEnum.getByIsAdmin(isAdmin);

        // 必须有管理员权限
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum)) {
            // 用户没有管理员权限，拒绝
            if (!UserRoleEnum.ADMIN.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "权限不足，只有管理员可以创建客户");
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

